/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ftpdownload;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

//this class is responsible for  the Logging Operation
public class LogFile 
{
    public static void log(String owner, String logtxt) 
    {
        PrintWriter fw;
        OSDetector osd=new OSDetector();
        String osslash=null;
        Document config=null;
        try 
        {
            SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
            String filename = sdf.format(new Date());
            
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            if(osd.isWindows())
            {
                osslash="\\";
                config = builder.parse("C:\\Users\\A7med Kotb\\Documents\\NetBeansProjects\\trunk\\Book Dimension Project\\src\\java\\Configuration\\winconfig.xml");
            }
            if(osd.isUnix())
            {
                osslash="/";
                config = builder.parse("/home/ahmed/NetBeansProjects/trunk/Book Dimension Project/src/java/Configuration/linconfig.xml");
            }
            Element logpathelement = (Element) config.getElementsByTagName("log-path").item(0);
            File mydir=new File(logpathelement.getTextContent() +osslash+filename);
            mydir.mkdir();
            String path = mydir+osslash+ filename + ".txt";
            System.out.println(path);
            FileOutputStream out = new FileOutputStream(path, true);
            PrintWriter pw = new PrintWriter(out, true);
            pw.println(owner + " " + logtxt + "<br>");
            pw.close();
            out.close();
        } 
        catch (Exception ex) 
        {
            Logger.getLogger(LogFile.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void getNextLogs(HttpServletResponse response, Date d, long skip) 
    {
        OSDetector osd=new OSDetector();
        String osslash=null;
        Document config=null;
        try 
        {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            if(osd.isWindows())
            {
                osslash="\\";
                config = builder.parse("C:\\Users\\A7med Kotb\\Documents\\NetBeansProjects\\trunk\\Book Dimension Project\\src\\java\\Configuration\\winconfig.xml");
            }
            if(osd.isUnix())
            {
                osslash="/";
                config = builder.parse("/home/ahmed/NetBeansProjects/trunk/Book Dimension Project/src/java/Configuration/linconfig.xml");
            }
            Element logpathelement = (Element) config.getElementsByTagName("log-path").item(0);
            SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
            String logpath = logpathelement.getTextContent() + osslash + df.format(d)+osslash+df.format(d) + ".txt";
            PrintWriter writer = response.getWriter();
            FileReader fs = new FileReader(logpath);
            File f = new File(logpath);
            BufferedReader reader = new BufferedReader(fs);
            if (skip >= f.length()) 
            {
                writer.print("No Data Available Next ....");
                return;
            } 
            else if (skip < 0) 
            {
                writer.print("No Data Available Previous ....");
                return;
            }
            String txt;
            reader.skip(skip);
            int no = 0;
            while ((txt = reader.readLine()) != null) 
            {
                if (no < 100) 
                {
                    writer.println(txt);
                    //    skip+=txt.length()+2;
                    no++;
                } 
                else 
                {
                    break;
                }
            }
            //     result.setLogs(logs);
            //     result.setNextSkip(skip);
        } 
        catch (Exception ex) 
        {
            Logger.getLogger(LogFile.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void getNextLogs(HttpServletResponse response, HttpServletRequest request, String providername, Date d, String operation) 
    {
        OSDetector osd=new OSDetector();
        String osslash=null;
        Document config=null;
        try 
        {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            if(osd.isWindows())
            {
                osslash="\\";
                config = builder.parse("C:\\Users\\A7med Kotb\\Documents\\NetBeansProjects\\trunk\\Book Dimension Project\\src\\java\\Configuration\\winconfig.xml");
            }
            if(osd.isUnix())
            {
                osslash="/";
                config = builder.parse("/home/ahmed/NetBeansProjects/trunk/Book Dimension Project/src/java/Configuration/linconfig.xml");
            }
            Element logpathelement = (Element) config.getElementsByTagName("log-path").item(0);
            SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
            String logpath = logpathelement.getTextContent() + osslash + df.format(d)+osslash+df.format(d) + ".txt";
            //Directory
            PrintWriter writer = response.getWriter();
            long skip = 0;
            Vector<Long> steps = new Vector<Long>();
            steps.add(0l);
            if (request.getSession(true).getAttribute("steps") != null) 
            {
                steps = (Vector<Long>) request.getSession(true).getAttribute("steps");
                if (operation.equals("back")) 
                {
                    System.out.println("sizzzzzzzzzzze=" + steps.size());
                    if (steps.size() <= 2) 
                    {
                        request.getSession(true).removeAttribute("steps");
                        writer.print("No Data Available Previous ....");
                        return;
                    } 
                    else 
                    {
                        steps.remove(steps.size() - 1);
                        skip = steps.get(steps.size() - 2);
                    }
                } 
                else if (operation.equals("next")) 
                {
                    skip = steps.get(steps.size() - 1);
                } 
                else if (operation.equals("start")) 
                {
                    skip = 0;
                    steps = new Vector<Long>();
                    steps.add(0l);
                    request.getSession(true).removeAttribute("steps");
                }
            }
            System.out.println("previous skip =" + skip);
            // Vector<String> logs=new Vector<String>();
            FileReader fs = new FileReader(logpath);
            File f = new File(logpath);
            BufferedReader reader = new BufferedReader(fs);
            if (skip >= f.length()) 
            {
                writer.print("No Data Available Next ....");
                steps.add(skip);
                request.getSession(true).setAttribute("steps", steps);
                return;
            } 
            else if (skip < 0)
            {
                writer.print("No Data Available Previous ....");
                return;
            }
            String txt;
            reader.skip(skip);
            int no = 0;
            while ((txt = reader.readLine()) != null) 
            {
                if (no < 100) 
                {
                    boolean first=txt.contains(providername);
                    if(first==true)
                    {
                        writer.println(txt);
                        System.out.println(txt);
                        skip += txt.length() + 2;
                        no++;
                    }
//                    String first = txt.split(" ")[0];
//                    if (first.equalsIgnoreCase(providername)) 
//                    {
//                        writer.println(txt);
//                        System.out.println(txt);
//                        skip += txt.length() + 2;
//                        no++;
//                    }

                } 
                else 
                {
                    break;
                }
            }
            System.out.println("add steps..........");
            if (operation.equals("next") || operation.equals("start")) 
            {
                steps.add(skip);
                request.getSession(true).setAttribute("steps", steps);
            }
            //     result.setLogs(logs);
            //     result.setNextSkip(skip);
            System.out.println("skip=" + skip);
            reader.close();
            fs.close();
        } 
        catch (Exception ex) 
        {
            Logger.getLogger(LogFile.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void main(String[] args) 
    {
    }
}
